#include "rtcopt.h"
#include <linux/rtc.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <inttypes.h>
#include <unistd.h>

// #define RTC_DEV_NAME_STR "/dev/rtc0" //"/dev/misc/rtc1"


static tmdateType tmRtcToDate(struct rtc_time *rtcTm)
{
    tmdateType tmpdate = {0};
    tmpdate.year = rtcTm->tm_year + 1900;
    tmpdate.month = rtcTm->tm_mon + 1;
    tmpdate.day = rtcTm->tm_mday;
    tmpdate.week = rtcTm->tm_wday;
    tmpdate.yday = rtcTm->tm_yday;
    tmpdate.hour = rtcTm->tm_hour;
    tmpdate.minute = rtcTm->tm_min;
    tmpdate.second = rtcTm->tm_sec;
    return tmpdate;
}

static struct rtc_time tmDateToRtc(tmdateType *tdate)
{
    struct rtc_time tmprtc = {0};
    tmprtc.tm_year = tdate->year - 1900;
    tmprtc.tm_mon = tdate->month - 1;
    tmprtc.tm_mday = tdate->day;
    tmprtc.tm_hour = tdate->hour;
    tmprtc.tm_min = tdate->minute;
    tmprtc.tm_sec = tdate->second;
    tmprtc.tm_wday = tdate->week;
    tmprtc.tm_yday = tdate->yday;
    return tmprtc;
}

int rtcDevTmRead(tmdateType *getdt, const char *rtcdev)
{
    int tmpflag = 0;
    if (!getdt)
    {
        printf("date null\n");
        return -1;
    }
    int rtcfd = open(rtcdev, O_RDWR);
    if (rtcfd < 0)
    {
        printf("get rtc open err:%s, %s\n", rtcdev, strerror(errno));
        return -1;
    }
    do
    {
        struct rtc_time rtc_tm;
        if (ioctl(rtcfd, RTC_RD_TIME, &rtc_tm) < 0)
        {
            printf("rtc RTC_RD_TIME:%s, %s\n", rtcdev, strerror(errno));
            tmpflag = -1;
            break;
        }
        getdt[0] = tmRtcToDate(&rtc_tm);
        // printf("rtcDevTmRead[%d-%d-%d %d:%d:%d]\n", getdt->year, getdt->month, getdt->day, getdt->hour, getdt->minute, getdt->second);
    } while (0);
    close(rtcfd);
    return tmpflag;
}

int rtcDevTmWrite(tmdateType *setdt, const char *rtcdev)
{
    int tmpflag = 0;
    if (!setdt)
    {
        printf("date null\n");
        return -1;
    }
    int rtcfd = open(rtcdev, O_RDWR);
    if (rtcfd < 0)
    {
        printf("set rtc open err:%s, %s\n", rtcdev, strerror(errno));
        return -1;
    }
    do
    {
        struct rtc_time rtc_tm = tmDateToRtc(setdt);
        if (ioctl(rtcfd, RTC_SET_TIME, &rtc_tm) < 0)
        {
            printf("rtc RTC_SET_TIME:%s, %s\n", rtcdev, strerror(errno));
            tmpflag = -1;
            break;
        }
    } while (0);
    close(rtcfd);
    return tmpflag;
}
